﻿using DiLe.Mes.Application.Common.Equipment;
using DiLe.Mes.Application.Local;
using DiLe.Mes.Local.Jobs;
using DiLe.Mes.Model.Cloud.Dashboard.Statistics;
using DiLe.Mes.Model.Cloud.Statistics;
using DiLe.Mes.Model.Common.APP;
using DiLe.Mes.Model.Common.Equipment.Entity.Manage;
using DiLe.Mes.Model.Common.Mould.Entity.Info;
using DiLe.Mes.Model.Common.Organization.Entity;
using DiLe.Mes.Model.Common.Process.Entity;
using MapleLeaf.Core.Cryptogram;
using MapleLeaf.Core.Excel;
using Microsoft.AspNetCore.Authorization;

namespace DiLe.Mes.Local.Controllers {
    /// <summary>
    /// 
    /// </summary>
    [ApiExplorerSettings(GroupName = ApiLocalGroupConst.Other)]
    public class InitController : ApiBaseController {

        private readonly LocalClient _localClient;
        private readonly EquipmentManageClient _equipmentManage;
        private readonly IWebHostEnvironment _webHostEnvironment;
        /// <summary>
        /// 
        /// </summary>
        public InitController(LocalClient localClient, IWebHostEnvironment webHostEnvironment, EquipmentManageClient equipmentManageClient) {
            _localClient = localClient;
            _equipmentManage = equipmentManageClient;
            _webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 同步请求
        /// </summary>
        [HttpGet, AllowAnonymous]
        public async Task<ApiResult> SynchronousRequest() {
            HttpClientHelper helper = new();
            var url = AppHelper.GetConfig("AppSetting", "CloudUrl");
            var appkey = AppHelper.GetConfig("AppSetting", "Appkey");
            string key = MD5Helper.CalculateMD5(appkey);
            // 发起 GET 请求
            string response = await helper.GetAsync($"{url}/api/init/SynchronousReturn?key={key}");
            var res = JsonConvert.DeserializeObject<ApiResult<SynchronousInfo>>(response);
            if (res == null || res.code != 200 || res.data == null) {
                return Fail("同步失败！");
            }
            var userInfos = res.data.UserInfos;
            if (!userInfos.None()) {
                await SqlSugarHelper.MasterDb.Deleteable<UserEntity>().ExecuteCommandAsync();
                await SqlSugarHelper.MasterDb.Insertable(userInfos).ExecuteCommandAsync();
            }
            var roleInfos = res.data.RoleInfos;
            if (!roleInfos.None()) {
                await SqlSugarHelper.MasterDb.Deleteable<RoleEntity>().ExecuteCommandAsync();
                await SqlSugarHelper.MasterDb.Insertable(roleInfos).ExecuteCommandAsync();
            }


            if (!res.data.EquipmentInfoList.None()) {
                await SqlSugarHelper.MasterDb.Deleteable<EquipmentInfoEntity>().ExecuteCommandAsync();
                await SqlSugarHelper.MasterDb.Insertable(res.data.EquipmentInfoList).ExecuteCommandAsync();
            }
            if (!res.data.EquipmentTypeList.None()) {
                await SqlSugarHelper.MasterDb.Deleteable<EquipmentTypeEntity>().ExecuteCommandAsync();
                await SqlSugarHelper.MasterDb.Insertable(res.data.EquipmentTypeList).ExecuteCommandAsync();
            }
            if (!res.data.EquipmentStatusList.None()) {
                await SqlSugarHelper.MasterDb.Deleteable<EquipmentStatusEntity>().ExecuteCommandAsync();
                await SqlSugarHelper.MasterDb.Insertable(res.data.EquipmentStatusList).ExecuteCommandAsync();
            }


            if (!res.data.MouldInfoList.None()) {
                await SqlSugarHelper.MasterDb.Deleteable<MouldInfoEntity>().ExecuteCommandAsync();
                await SqlSugarHelper.MasterDb.Insertable(res.data.MouldInfoList).ExecuteCommandAsync();
            }
            if (!res.data.MouldTypeList.None()) {
                await SqlSugarHelper.MasterDb.Deleteable<MouldTypeEntity>().ExecuteCommandAsync();
                await SqlSugarHelper.MasterDb.Insertable(res.data.MouldTypeList).ExecuteCommandAsync();
            }
            if (!res.data.MouldStatusList.None()) {
                await SqlSugarHelper.MasterDb.Deleteable<MouldStatusEntity>().ExecuteCommandAsync();
                await SqlSugarHelper.MasterDb.Insertable(res.data.MouldStatusList).ExecuteCommandAsync();
            }
            if (!res.data.ProcessList.None()) {//制程
                await SqlSugarHelper.MasterDb.Deleteable<ProcessEntity>().ExecuteCommandAsync();
                await SqlSugarHelper.MasterDb.Insertable(res.data.ProcessList).ExecuteCommandAsync();
            }
            if (!res.data.EquipmentRegisterList.None()) {//设备注册
                await SqlSugarHelper.MasterDb.Deleteable<EquipmentRegisterEntity>().ExecuteCommandAsync();
                await SqlSugarHelper.MasterDb.Insertable(res.data.EquipmentRegisterList).ExecuteCommandAsync();
            }
            return Success();
        }

        /// <summary>
        /// 设备运行时间统计
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public async Task<ApiResult> PushEquipmentStatisticsAsync(string date) {
            DateTime currentDate = DateTime.Parse(date).Date;
            var where = Expressionable.Create<EquipmentOperationEntity>();

            var starTime = currentDate.AddHours(7);
            var endTime = currentDate.AddDays(1).AddHours(9);
            where.And(p => p.CreateTime >= starTime);
            where.And(p => p.CreateTime <= endTime);

            var list = await SqlSugarHelper.MasterDb.Queryable<EquipmentOperationEntity>().Where(where.ToExpression()).ToListAsync();
            if (list.None()) {
                return Fail();
            }
            var dataMap = list.GroupBy(x => x.DeviceNo).Select(x => (x.Key, x.OrderBy(y => y.CreateTime).ToList())).ToList();

            var pushDatas = new List<EquipmentStatisticsEntity>();
            foreach (var item in dataMap) {
                var dcount = item.Item2.Count(x => x.CreateTime <= currentDate.AddHours(19));
                var ncount = item.Item2.Count(x => x.CreateTime >= currentDate.AddHours(20).AddMinutes(-1));
                //日班
                EquipmentStatisticsEntity? dm = null;
                //夜班
                EquipmentStatisticsEntity? nm = null;
                if (dcount > 0 && ncount > 0) {
                    dm = GetDayEquipmentStatistics(item.Key, currentDate, item.Item2, false);
                    nm = GetNightEquipmentStatistics(item.Key, currentDate, item.Item2, false);
                } else if (dcount > 0) {
                    dm = GetDayEquipmentStatistics(item.Key, currentDate, item.Item2, true);
                } else if (ncount > 0) {
                    nm = GetNightEquipmentStatistics(item.Key, currentDate, item.Item2, true);
                }

                if (dm?.ActualWorkingHour > 0) {
                    if (dm.Date == null) {
                        dm.Date = currentDate;
                    }
                    dm.FactoryId = AppHelper.AppSettingInfo.AppId.ToLong();
                    pushDatas.Add(dm);
                }

                if (nm?.ActualWorkingHour > 0) {
                    if (nm.Date == null) {
                        nm.Date = currentDate;
                    }
                    nm.FactoryId = AppHelper.AppSettingInfo.AppId.ToLong();
                    pushDatas.Add(nm);
                }
            }

            HttpClientHelper helper = new();
            var url = AppHelper.GetConfig("AppSetting", "CloudUrl");
            // 发起 Post 请求
            string response = await helper.PostJsonAsync($"{url}/api/init/SynchronousEquipmentStatistics", pushDatas.ToJosn());
            var res = JsonConvert.DeserializeObject<ApiResult>(response);
            if (res == null || res.code != 200) {
                return Fail("同步失败！");
            }
            return Success();
        }
        /// <summary>
        /// 日班
        /// </summary>
        /// <returns></returns>
        private static EquipmentStatisticsEntity GetDayEquipmentStatistics(string deviceno, DateTime date, List<EquipmentOperationEntity> list, bool iserror) {
            var dataList = new List<EquipmentStatisticsEntity>();
            var m1 = new EquipmentStatisticsEntity {//日班
                DeviceNo = deviceno,
                Date = date,
                Classes = "8:00~20:00",
                ActualWorkingHour = 0
            };
            DateTime start = date.AddHours(8).AddMinutes(-1);
            DateTime end = date.AddHours(20);
            if (iserror) {
                //7~21 误差60分钟
                start = date.AddHours(7);
                end = date.AddHours(21);
            }
            list = [.. list.Where(x => x.CreateTime >= start && x.CreateTime <= end).OrderBy(t => t.CreateTime)];

            for (int i = 0; i < list.Count; i++) {
                var ism = list[i];
                if (i == 0) {
                    m1.EquipmentStartTime = ism.StartTime;
                }
                if (!ism.IsFinish || ism.EndTime == null) {
                    if (i == list.Count - 1) {
                        ism.EndTime = date.AddHours(20);
                    } else {
                        var nism = list[i + 1];
                        ism.EndTime = nism.StartTime;
                    }
                }
                if (!iserror) {
                    if (ism.EndTime > date.AddHours(20)) {
                        ism.EndTime = date.AddHours(20);
                    }
                }

                if (m1.EquipmentEndTime == null || m1.EquipmentEndTime < ism.EndTime) {
                    m1.EquipmentEndTime = ism.EndTime;
                }
                TimeSpan? ts = ism.EndTime - ism.StartTime;
                m1.ActualWorkingHour += (decimal)(ts?.TotalHours ?? 0);
            }
            if (m1.ActualWorkingHour > 12) {
                m1.ActualWorkingHour = 12;
            }
            return m1;
        }
        /// <summary>
        /// 夜班
        /// </summary>
        /// <returns></returns>
        private static EquipmentStatisticsEntity GetNightEquipmentStatistics(string deviceno, DateTime date, List<EquipmentOperationEntity> list, bool iserror) {
            var dataList = new List<EquipmentStatisticsEntity>();
            var m1 = new EquipmentStatisticsEntity {//日班
                DeviceNo = deviceno,
                Date = date,
                Classes = "20:00~8:00",
                ActualWorkingHour = 0
            };
            DateTime start = date.AddHours(20).AddMinutes(-1);
            DateTime end = date.AddHours(32);
            if (iserror) {
                //19~9 误差60分钟
                start = date.AddHours(19);
                end = date.AddHours(33);
            }
            list = [.. list.Where(x => x.CreateTime >= start && x.CreateTime <= end).OrderBy(t => t.CreateTime)];
            for (int i = 0; i < list.Count; i++) {
                var ism = list[i];
                if (i == 0) {
                    m1.EquipmentStartTime = ism.StartTime;
                }
                if (!ism.IsFinish || ism.EndTime == null) {
                    if (i == list.Count - 1) {
                        ism.EndTime = date.AddHours(32);
                    } else {
                        var nism = list[i + 1];
                        ism.EndTime = nism.StartTime;
                    }
                }
                if (!iserror) {
                    if (ism.EndTime > date.AddHours(32)) {
                        ism.EndTime = date.AddHours(32);
                    }
                }
                if (m1.EquipmentEndTime == null || m1.EquipmentEndTime < ism.EndTime) {
                    m1.EquipmentEndTime = ism.EndTime;
                }

                TimeSpan? ts = ism.EndTime - ism.StartTime;
                m1.ActualWorkingHour += (decimal)(ts?.TotalHours ?? 0);
            }

            if (m1.ActualWorkingHour > 12) {
                m1.ActualWorkingHour = 12;
            }
            return m1;
        }




        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public async Task<ApiResult> PushEquipmentOutputStatisticsAsync(string date) {
            DateTime currentDate = DateTime.Parse(date);

            var where = Expressionable.Create<EquipmentOperationEntity>();
            var startDate = currentDate.AddHours(8);
            var endDate = currentDate.AddHours(32);
            where.And(p => p.OperationDateTime == currentDate);

            var eolist = await SqlSugarHelper.MasterDb.Queryable<EquipmentOperationEntity>().Where(where.ToExpression()).ToListAsync();
            if (eolist.None()) {
                return Fail();
            }
            var infos = _equipmentManage.GetEquipmentInfoModelList();
            var list = await _equipmentManage.GetEquipmentTypeListAsync();
            var pushDatas = new List<EquipmentOutputStatisticsEntity>();
            foreach (var info in infos) {
                var items = eolist.Where(x => x.DeviceNo == info.EquipmentSign).OrderBy(x => x.CreateTime);
                if (items.None()) {
                    continue;
                }
                DateTime? start = items.FirstOrDefault()?.StartTime;
                if (start == null) {
                    continue;
                }
                if (start < startDate) {
                    start = startDate;
                }
                var m = new EquipmentOutputStatisticsEntity() {
                    EquipmentCode = info.EquipmentCode,
                    EquipmentName = info.EquipmentName,
                    Date = currentDate
                };
                var name = GetParentType(info.EquipmentTypeId, list);
                FillStartFormingTotalTimes(m, info.EquipmentSign, name, start.Value);

                DateTime? endtime = items.LastOrDefault()?.EndTime;
                if (endtime == null) {
                    FillEndFormingTotalTimes(m, info.EquipmentSign, name, DateTime.Now);
                } else if (endtime > endDate) {
                    FillEndFormingTotalTimes(m, info.EquipmentSign, name, endDate);
                } else {
                    FillEndFormingTotalTimes(m, info.EquipmentSign, name, endtime.Value);
                }
                m.MouldCavityNum = 0;
                m.FactoryId = AppHelper.AppSettingInfo.AppId.ToLong();
                pushDatas.Add(m);
            }

            HttpClientHelper helper = new();
            var url = AppHelper.GetConfig("AppSetting", "CloudUrl");
            // 发起 Post 请求
            string response = await helper.PostJsonAsync($"{url}/api/init/SynchronousEquipmentOutputStatistics", pushDatas.ToJosn());
            var res = JsonConvert.DeserializeObject<ApiResult>(response);
            if (res == null || res.code != 200) {
                return Fail("同步失败！");
            }

            return Success();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private void FillStartFormingTotalTimes(EquipmentOutputStatisticsEntity info, string sign, string name, DateTime dateTime) {
            switch (name) {
                case "成型机":
                    var data = _localClient.GetCurrentTimePointInfo(sign, dateTime);
                    info.StartMouldNumber = data?.FormingTotalTimes?.ToInt() ?? 0;
                    info.StartEnergy = data?.EeTotal?.ToInt();
                    break;
                case "AOI":
                    var dataAOI = _localClient.GetCurrentTimeAOIPointInfo(sign, dateTime);
                    info.StartNumber = dataAOI?.CheckTotalTimes?.ToInt() ?? 0;
                    info.StartCheckNG = dataAOI?.CheckNGNo?.ToInt() ?? 0;
                    break;
                case "切边机":
                case "冲切机":
                    var dataTrim = _localClient.GetCurrentTrimPointInfoList(sign, dateTime);
                    info.StartMouldNumber = dataTrim?.TrimingTotalTimes?.ToInt() ?? 0;
                    break;
                case "生产线":
                    var data1311 = _localClient.GetCurrent1311PointInfo(sign, dateTime);
                    info.StartMouldNumber = data1311?.FormingTotalTimes?.ToInt() ?? 0;
                    info.StartNumber = data1311?.StackingTotalNum?.ToInt() ?? 0;
                    info.StartEnergy = data1311?.EeTotal?.ToInt();
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private void FillEndFormingTotalTimes(EquipmentOutputStatisticsEntity info, string sign, string name, DateTime dateTime) {
            switch (name) {
                case "成型机":
                    var data = _localClient.GetCurrentTimePointInfo(sign, dateTime);
                    info.EndMouldNumber = data?.FormingTotalTimes?.ToInt() ?? 0;
                    info.EndEnergy = data?.EeTotal?.ToInt();
                    break;
                case "AOI":
                    var dataAOI = _localClient.GetCurrentTimeAOIPointInfo(sign, dateTime);
                    info.EndNumber = dataAOI?.CheckTotalTimes?.ToInt() ?? 0;
                    info.EndCheckNG = dataAOI?.CheckNGNo?.ToInt() ?? 0;
                    break;
                case "切边机":
                case "冲切机":
                    var dataTrim = _localClient.GetCurrentTrimPointInfoList(sign, dateTime);
                    info.EndMouldNumber = dataTrim?.TrimingTotalTimes?.ToInt() ?? 0;
                    break;
                case "生产线":
                    var data1311 = _localClient.GetCurrent1311PointInfo(sign, dateTime);
                    info.EndMouldNumber = data1311?.FormingTotalTimes?.ToInt() ?? 0;
                    info.EndNumber = data1311?.StackingTotalNum?.ToInt() ?? 0;
                    info.EndEnergy = data1311?.EeTotal?.ToInt();
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="typeid"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        private static string GetParentType(long typeid, List<EquipmentTypeEntity> list) {
            string? name = "";
            var data = list.FirstOrDefault(p => p.Id == typeid);
            if (data?.ParentId != null && data?.ParentId > 0) {
                name = GetParentType(data.ParentId.Value, list);
            } else {
                name = data?.Name;
            }
            return name ?? "";
        }

        /// <summary>
        /// 查询运行时间统计
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public async Task<ApiResult<List<EquipmentOperationModel>>> QueryEquipmentStatisticsAsync(string date) {
            var datalist = await GetEquipmentOperationModelsAsync(date);
            return Success(datalist);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        private async Task<List<EquipmentOperationModel>> GetEquipmentOperationModelsAsync(string date) {
            DateTime currentDate = DateTime.Parse(date).Date;
            var where = Expressionable.Create<EquipmentOperationEntity>();

            //DateTime startDate = currentDate.AddHours(7);
            //DateTime endDate = currentDate.AddHours(33);
            //where.And(p => p.CreateTime >= startDate);
            //where.And(p => p.CreateTime <= endDate);
            where.And(p => p.OperationDateTime == currentDate);
            var infos = _equipmentManage.GetEquipmentInfoModelList();

            var list = await SqlSugarHelper.MasterDb.Queryable<EquipmentOperationEntity>().Where(where.ToExpression()).ToListAsync();

            var datalist = new List<EquipmentOperationModel>();
            foreach (var item in list) {
                var info = infos?.FirstOrDefault(x => x.EquipmentSign == item.DeviceNo);

                var m = item.Adapt<EquipmentOperationModel>();
                m.EquipmentCode = info?.EquipmentCode ?? "";
                m.EquipmentName = info?.EquipmentName ?? "";
                m.EquipmentTypeName = info?.EquipmentTypeName ?? "";
                if (m.EndTime != null) {
                    TimeSpan timeSpan = m.EndTime.Value - m.StartTime;
                    m.WorkingHour = Math.Round(timeSpan.TotalHours, 2);
                }
                datalist.Add(m);
            }
            return datalist;
        }

        /// <summary>
        /// 导出运行时间统计
        /// </summary>
        /// <returns></returns>
        //[HttpGet, AllowAnonymous]
        //public async Task<IActionResult> ExportEquipmentStatisticsAsync(string date) {
        // var list = await GetEquipmentOperationModelsAsync(date);

        //var dic = new List<ExportColumn>() {
        //    new(){ Field = "" ,Title="设备编号" },
        //    new(){ Field = "" ,Title="设备名称" },
        //    new(){ Field = "" ,Title="设备标识" },
        //    new(){ Field = "" ,Title="设备类型" },
        //    new(){ Field = "" ,Title="开始时间" }
        //};


        //// 创建第一个sheet
        //ISheet sheet = workbook.CreateSheet("设备运行统计");


        ////创建表头行
        //var headerRow = sheet.CreateRow(0);


        //ICell cell_0 = headerRow.CreateCell(0);
        //cell_0.SetCellValue("设备编号");
        //ICell cell_1 = headerRow.CreateCell(1);
        //cell_1.SetCellValue("设备名称");
        //ICell cell_2 = headerRow.CreateCell(2);
        //cell_2.SetCellValue("设备标识");
        //ICell cell_3 = headerRow.CreateCell(3);
        //cell_3.SetCellValue("设备类型");
        //ICell cell_4 = headerRow.CreateCell(4);
        //cell_4.SetCellValue("开始时间");
        //ICell cell_5 = headerRow.CreateCell(5);
        //cell_5.SetCellValue("结束时间");
        //ICell cell_6 = headerRow.CreateCell(6);
        //cell_6.SetCellValue("工时");

        //// 
        //for (int i = 0; i < 6; i++) {
        //    sheet.AutoSizeColumn(i);
        //    sheet.SetColumnWidth(i, 256 * 30);
        //}

        //for (int i = 0; i < list.Count; i++) {
        //    var data = list[i];
        //    IRow row = sheet.CreateRow(i + 1);
        //    ICell rcell_0 = row.CreateCell(0);
        //    rcell_0.SetCellValue(data.EquipmentCode);
        //    ICell rcell_1 = row.CreateCell(1);
        //    rcell_1.SetCellValue(data.EquipmentName);
        //    ICell rcell_2 = row.CreateCell(2);
        //    rcell_2.SetCellValue(data.DeviceNo);
        //    ICell rcell_3 = row.CreateCell(3);
        //    rcell_3.SetCellValue(data.EquipmentTypeName);


        //    ICell rcell_4 = row.CreateCell(4);
        //    rcell_4.SetCellValue(data.StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
        //    ICell rcell_5 = row.CreateCell(5);
        //    if (data.EndTime != null) {
        //        rcell_5.SetCellValue(data.EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));
        //        ICell rcell_6 = row.CreateCell(6);
        //        TimeSpan timeSpan = data.EndTime.Value - data.StartTime;
        //        rcell_6.SetCellValue(Math.Round(timeSpan.TotalHours, 2));
        //    }
        //}
        //var excelFileName = $"设备Dashboard({DateTime.Now:yyyyMMdd}).xlsx";
        //var filePath = Path.Combine(_webHostEnvironment.WebRootPath, excelFileName);

        ////将Execel 文件写入磁盘
        //using (var f = System.IO.File.OpenWrite(filePath)) {
        //    workbook.Write(f);
        //}
        ////将Excel 文件作为下载返回给客户端
        //var bytes = System.IO.File.ReadAllBytes(filePath);

        //// 设置响应头信息
        //HttpContext.Response.Headers.AccessControlExposeHeaders = "Content-Disposition";

        //return File(bytes, "application/octet-stream", excelFileName);



        //}
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public ApiResult Test() {

            //// 获取 UTC+08:00 的时区信息
            //TimeZoneInfo utc8TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai");

            //// 将当前时间转换为中国标准时间
            //DateTime utc8Time = DateTime.Parse("2023-12-08 23:54:47.426");
            //DateTime chinaTime = TimeZoneInfo.ConvertTime(utc8Time, utc8TimeZone, TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"));

            //Console.WriteLine("当前 UTC+08:00 时间： " + utc8Time);
            //Console.WriteLine("中国标准时间： " + chinaTime);
            return Success(AppHelper.AppSettingInfo);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public async Task<ApiResult> PushEMPointStatistics(string date) {
            var currentdate = DateTime.Parse(date).Date;
            var datalist = await PointStatisticsHelper.GetEMPointStatisticsListAsync(currentdate);
            if (datalist.None()) {
                return Fail();
            }
            var dateStr = currentdate.ToString("yyyy-MM-dd HH:mm:ss");
            List<string> NameArr = [];
            var pushDatas = new List<EMPointStatisticsEntity>();
            foreach (var data in datalist) {
                int orderNum = 0;
                if (data.DeviceNo.Equals("电能表-1", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.NameArr1;
                    orderNum = 1;
                } else if (data.DeviceNo.Equals("电能表-2", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.NameArr2;
                    orderNum = 40;
                } else if (data.DeviceNo.Equals("电能表-6", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.NameArr6;
                    orderNum = 60;
                }
                var valueArr = data!.EcTotal.Split(",");
                if (valueArr.Length < NameArr.Count) {
                    continue;
                }
                for (int i = 0; i < NameArr.Count; i++) {
                    var name = NameArr[i];
                    var value = valueArr[i];

                    var m = new EMPointStatisticsEntity {
                        ElectricEnergy = value,
                        Name = name,
                        OrderNumber = ++orderNum,
                        Date = dateStr,
                        FactoryId = AppHelper.AppSettingInfo.AppId.ToLong(),
                        Type = "电能表",
                    };
                    pushDatas.Add(m);
                }
            }
            HttpClientHelper helper = new();
            var url = AppHelper.GetConfig("AppSetting", "CloudUrl");
            // 发起 Post 请求
            string response = await helper.PostJsonAsync($"{url}/api/init/SynchronousEMPointStatistics", pushDatas.ToJosn());
            var res = JsonConvert.DeserializeObject<ApiResult>(response);
            if (res == null || res.code != 200) {
                return Fail("同步失败！");
            }
            return Success();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public async Task<ApiResult> PushFMPointStatistics(string date) {
            var currentdate = DateTime.Parse(date).Date;
            var dataList = await PointStatisticsHelper.GetFMPointStatisticsListAsync(currentdate);
            if (dataList.None()) {
                return Fail();
            }
            var dateStr = currentdate.ToString("yyyy-MM-dd HH:mm:ss");
            var pushDatas = new List<FMPointStatisticsEntity>();
            foreach (var data in dataList) {
                List<(int num, string name)> NameArr = [];
                if (data.DeviceNo.Equals("流量计-3", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.FMNameArr3;
                } else if (data.DeviceNo.Equals("流量计-5", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.FMNameArr5;
                } else if (data.DeviceNo.Equals("流量计-2", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.FMNameArr2;
                }
                var valueArr = data!.FlowTotal.Split(",");
                if (valueArr.Length < NameArr.Count) {
                    continue;
                }
                for (int i = 0; i < NameArr.Count; i++) {
                    var (num, name) = NameArr[i];
                    var value = valueArr[i];

                    var m = new FMPointStatisticsEntity {
                        FlowRate = value,
                        Name = name,
                        OrderNumber = num,
                        Date = dateStr,
                        FactoryId = AppHelper.AppSettingInfo.AppId.ToLong(),
                        Type = "流量表",
                    };
                    pushDatas.Add(m);
                }
            }

            HttpClientHelper helper = new();
            var url = AppHelper.GetConfig("AppSetting", "CloudUrl");
            // 发起 Post 请求
            string response = await helper.PostJsonAsync($"{url}/api/init/SynchronousFMPointStatistics", pushDatas.ToJosn());
            var res = JsonConvert.DeserializeObject<ApiResult>(response);
            if (res == null || res.code != 200) {
                return Fail("同步失败！");
            }
            return Success();
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class SynchronousInfo {
        /// <summary>
        /// 
        /// </summary>
        public List<UserEntity> UserInfos { set; get; }
        /// <summary>
        /// 
        /// </summary>
        public List<RoleEntity> RoleInfos { set; get; }

        /// <summary>
        /// 设备档案
        /// </summary>
        public List<EquipmentInfoEntity> EquipmentInfoList { set; get; }
        /// <summary>
        /// 设备类型
        /// </summary>
        public List<EquipmentTypeEntity> EquipmentTypeList { set; get; }
        /// <summary>
        /// 设备状态
        /// </summary>
        public List<EquipmentStatusEntity> EquipmentStatusList { set; get; }

        /// <summary>
        /// 模具档案
        /// </summary>
        public List<MouldInfoEntity> MouldInfoList { set; get; }
        /// <summary>
        /// 模具类型
        /// </summary>
        public List<MouldTypeEntity> MouldTypeList { set; get; }
        /// <summary>
        /// 模具状态
        /// </summary>
        public List<MouldStatusEntity> MouldStatusList { set; get; }
        /// <summary>
        /// 制程
        /// </summary>
        public List<ProcessEntity> ProcessList { set; get; }

        /// <summary>
        /// 注册信息
        /// </summary>
        public List<EquipmentRegisterEntity> EquipmentRegisterList { set; get; }


    }
    /// <summary>
    /// 
    /// </summary>
    public class EquipmentOperationModel : EquipmentOperationEntity {
        /// <summary>
        /// 
        /// </summary>
        public string EquipmentName { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string EquipmentTypeName { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string EquipmentCode { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public double WorkingHour { get; set; }
    }
}
